package cn.itcast.bos.web.action.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.UserService;
import cn.itcast.bos.web.action.commom.BaseAction;
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User> {
	@Action(value="login",results=
		{@Result(name="success",type
		="json")})
	public String login(){
		//用户名和密码都保存在model中
		//基于shiro实现登录
		Subject subject = SecurityUtils.getSubject();
		AuthenticationToken token = new UsernamePasswordToken(model.getUsername(),model.getPassword());
		Map<String,Object> result = new HashMap<String,Object>();
		try {
			subject.login(token);
			result.put("success",true);

		} catch (UnknownAccountException e) {
			result.put("success",false);
			result.put("msg","用户名不存在");
		}catch (IncorrectCredentialsException e){
			result.put("success",false);
			result.put("msg","密码不正确");
		}catch (Exception e){
			result.put("success",false);
			result.put("msg","现在服务器正忙请稍后再登");
		}
		ServletActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
		
		
	}
	@Action(value="user_logout",results=
		{@Result(name="success",location="login.html",type
		="redirect")})
	public String logout(){
		//用户名和密码都保存在model中
		//基于shiro实现登录
		Subject subject = SecurityUtils.getSubject();
	
			subject.logout();
			
			return SUCCESS;
		
		
	}
	
	@Autowired
	private UserService userService;
	@Action(value="user_list",results=
		{@Result(name="success",type
		="json")})
	public String list(){
		List<User> users = userService.findAll();
		ServletActionContext.getContext().getValueStack().push(users);
		return SUCCESS;
	}
	
	private String[] roleIds;
	
	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}
	@Action(value="user_save",results=
		{@Result(name="success",type
		="redirect",location="./pages/system/userlist.html")})
	public String save(){
		userService.save(model,roleIds);
		return SUCCESS;
	}
}
